package com.ln.store.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ln.store.domain.Cart;
import com.ln.store.domain.CartItem;
import com.ln.store.domain.Product;
import com.ln.store.service.ProductService;
import com.ln.store.service.Impl.ProductServiceImpl;
import com.ln.store.web.base.BaseServlet;

/**
 * Servlet implementation class CartServlet
 */
public class CartServlet extends BaseServlet {
	
	
	/**
	 * 添加商品到购物车
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 */
	public String addCartItemToCart(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//获取购物车
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if (cart == null)5 {
			cart = new Cart();
			//保存到session
			request.getSession().setAttribute("cart", cart);
		}
		//获取商品id，数量
		//根据商品id,获取商品对象
		String pid = request.getParameter("pid");
		int num = Integer.parseInt(request.getParameter("quantity"));
		
		System.out.println(pid+num);
		
		ProductService service = new ProductServiceImpl();
		Product product = service.findProductByPid(pid);
		
		//生成购物项
		CartItem cartItem = new CartItem();
		cartItem.setNum(num);
		cartItem.setProduct(product);
		
		//添加到购物车
		cart.addCartItem(cartItem);
		//重定向
		response.sendRedirect("/store_v5/jsp/cart.jsp");
		return null;
	}
}
